package com.mcxx.util;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mcxx.common.exception.BizException;
import com.yinhai.yhdcs.DcsClient;
import com.yinhai.yhdcs.client.cloudmodel.*;
import com.yinhai.yhdcs.constant.ClientConstant;
import com.yinhai.yhdcs.core.common.DcsServerException;
import com.yinhai.yhdcs.core.common.OSResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class UnifiedStorage {
    @Value("${yinhai.fileserver.uhossUrl:http://10.72.0.180:10000/yhdcs}")
    private String YHOSSURL;
    @Value("${yinhai.fileserver.accessKeyId:c29jaWV0eTE2Mjc0NjE1NzgwMjk=}")
    private String ACCESS_KEY_ID;
    @Value("${yinhai.fileserver.accessKeySecret:WV68e_6Rx4_5Fv7FpRdh3T5n9rEas2trtUt41Wvc}")
    private String ACCESS_KEY_SECRET = "";
    @Value("${yinhai.fileserver.bucketId:society-test}")
    private String BUCKET_ID;
    @Value("${yinhai.fileserver.checkBucketId:zhihuiminzheng}")
    private String Check_BUCKET_ID;
    @Value("${yinhai.fileserver.networkIntranet:false}")
    private Boolean NETWORK_INTRANET;
    
    @Value("${yinhai.fileserver.viewIntranet:false}")
    private Boolean GET_URL_INTRANET;
    @Value("${society.image.maxWidth:1920}")
    private int imageWidth;
    @Value("${society.image.maxHeight:1200}")
    private int imageHeight;

    private static DcsClient dcsClient;

    private static DcsClient dcsClient4URL;

    private static final Logger logger = LoggerFactory.getLogger(UnifiedStorage.class);

    public String testUpload() {
        File file = new File("D:\\home\\logo.png");
        UnifiedStorage storage = new UnifiedStorage();
        String imgKey = null;
        try {
            imgKey = storage.uploadFile(file);
        } catch (DcsServerException e) {
            System.out.println(e.getMessage());
        }
        System.out.println(imgKey);
        return imgKey;
    }

    public void testDownload(String objectId) {
        if(StringUtils.isEmpty(objectId)) {
            return;
        }

        UnifiedStorage storage = new UnifiedStorage();
        try {
            OSObject osObject = storage.download(objectId);
            InputStream stream = osObject.getContent();
            stream.close();
            byte[] content = new byte[1024];
            long size = 0;
            int len = 0;
            while((len=stream.read(content)) != -1) {
                size += len;
            }
            System.out.println(size);
        } catch (DcsServerException | IOException e) {
            System.out.println(e.getMessage());
        }
    }

    
    public String uploadFile(InputStream inputStream, String fileName) {

        inputStream = ImgUtil.compress4OriginSize(inputStream);

        //上传文件,objectKey可指定如a/b/file.exe或file.exe
        PutObjectRequest request = new PutObjectRequest(BUCKET_ID, inputStream, fileName);

        ObjectMetadata objectMetadata = new ObjectMetadata();

        objectMetadata.setObjectAcl(AccessControlList.PublicReadWrite);
        request.setObjectMetadata(objectMetadata);

        return upload(request);
    }

    
    public String uploadFile(File file) {
        try {
            FileInputStream inputStream = new FileInputStream(file);
            return this.uploadFile(inputStream, file.getName());
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage(), e);
            throw new BizException(e.getMessage());
        }
    }

    
    public OSObject downloadFile(String objectId, String bucketId) {
        if(StringUtils.isEmpty(bucketId)){
            bucketId = BUCKET_ID;
        }
        GetObjectRequest request = new GetObjectRequest(bucketId, objectId,null);

        return getClient().getObject(request);
    }

    
    public OSObject download(String objectId) {
        GetObjectRequest request = new GetObjectRequest(Check_BUCKET_ID, objectId,null);

        OSObject osObject = getClient().getObject(request);
        return osObject;
    }
    
    public String getFileUrl(String objectId, String bucketId) {
        if(StringUtils.isEmpty(bucketId)){
            bucketId = BUCKET_ID;
        }
        GetObjectRequest request = new GetObjectRequest(bucketId, objectId,null);
        OSResult objectView = getURLClient().getObjectView(request);

        return (String) objectView.getData();
    }

    
    public void deleteFile(String objectId) {
        getClient().deleteObjectById(BUCKET_ID, objectId);
    }

    
    public void deleteFile(List<String> objectIds) {
        DeleteObjectsRequest request = new DeleteObjectsRequest(BUCKET_ID, true, objectIds);
        getClient().deleteObject(request);
    }

    
    private String upload(PutObjectRequest request) {
        OSResult osResult = getClient().putObject(request);
        logger.info("上传结果：{}",JSON.toJSONString(osResult));

        dcsClient.shutdown();
        return (String) getData(osResult).get("objectid");
    }

    private JSONObject getData(OSResult osResult) {
        Class<? extends OSResult> clazz = osResult.getClass();
        JSONObject data = new JSONObject();
        try {
            Field dataField = clazz.getDeclaredField("data");
            dataField.setAccessible(true);
            data = (JSONObject) dataField.get(osResult);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return data;
    }

    
    private DcsClient getClient() {
        dcsClient = new DcsClient(YHOSSURL, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        if(NETWORK_INTRANET){
            dcsClient.setNetwork(Network.INTERNET);
        }

        return dcsClient;
    }

    
    private DcsClient getURLClient() {
        dcsClient4URL = new DcsClient(YHOSSURL, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        if(GET_URL_INTRANET){
            dcsClient4URL.setNetwork(Network.INTERNET);
        }
        return dcsClient4URL;
    }
}
